package com.gitee.huanminabc.fastboot.web.hook;

import com.alibaba.fastjson.JSONObject;
import com.gitee.huanminabc.fastboot.context.AppContext;
import com.gitee.huanminabc.fastboot.context.AppContextUtil;
import com.gitee.huanminabc.fastboot.load.hook.LoadAppConfigFinishHook;
import com.gitee.huanminabc.fastboot.web.config.AppServletConfig;
import com.gitee.huanminabc.fastboot.web.context.AppWebContext;
import com.gitee.huanminabc.fastboot.web.servlet.NettyServe;
import com.gitee.huanminabc.fastboot.web.servlet.ResponseBodyHandlerInterceptor;
import com.gitee.huanminabc.jcommon.reflect.BeanCopyUtil;
import com.gitee.huanminabc.jcommon.str.StringIdentifyUtil;
import com.gitee.huanminabc.nullchain.Null;

/**
 * 配置加载完毕后执行
 * @Author: huanmin
 * @Date: 2025/4/13 01:22
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
public class WebConfigFinishLifecycleHook implements LoadAppConfigFinishHook {
    @Override
    public void run() {
        //加载服务器配置
        serverConfigLoad();
        //响应打印
        AppWebContext.handlerInterceptors.add(new ResponseBodyHandlerInterceptor());
        //拦截器排序
        AppContextUtil.orderSort(AppWebContext.handlerInterceptors);
        //启动web服务
        NettyServe.start();
    }

    private static void serverConfigLoad() {
        //读取servlet配置
        JSONObject servletMap = AppContext.appConfigMap.getJSONObject("servlet");
        if (servletMap != null) {
            //转换为AppServletConfig
            AppServletConfig appServletConfig = servletMap.toJavaObject(AppServletConfig.class);
            BeanCopyUtil.copyIgnoreNull(appServletConfig, AppWebContext.appServletConfig);
        }
        //获取端口号-Dserver.port=8080
        Null.of(System.getProperty("servlet.port")).
                ifGo(StringIdentifyUtil::isPositiveNumeric).
                map(Integer::parseInt).
                ifPresent( AppWebContext.appServletConfig::setPort);

    }
}
